<template>
  <div>
    <el-table :data="tab" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>

      <el-table-column label="封面" width="100">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.bookImage"
            :preview-src-list="[scope.row.bookImage]"
          ></el-image>
        </template>
      </el-table-column>

      <el-table-column prop="bookName" label="书名"></el-table-column>
      <el-table-column prop="bookPrice" label="小计"></el-table-column>
      <el-table-column prop="number" label="购物车数量"></el-table-column>

      <el-table-column label="操作">
        <template slot-scope="scope">
          <div class="quantity-control">
            <el-button
              type="warning"
              icon="el-icon-minus"
              circle
              @click="modifyQuantity(scope.row.bookId, -1)"
            ></el-button>
            <span class="quantity-display">{{ scope.row.number }}</span>
            <el-button
              type="success"
              icon="el-icon-plus"
              circle
              @click="modifyQuantity(scope.row.bookId, 1)"
            ></el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="order-actions">
      <el-button type="warning" @click="confirmOrder" :disabled="selectedBooks.length === 0">一键下单</el-button>
    </div>

    <el-dialog :visible.sync="isDialogVisible" title="收货信息" width="50%" center>
      <el-table :data="gridData" style="width: 100%">
        <el-table-column prop="receiverName" label="收货人" width="150"></el-table-column>
        <el-table-column prop="receiverPhone" label="收货人手机号" width="150"></el-table-column>
        <el-table-column prop="addressInfo" label="收货人地址" width="300"></el-table-column>
        <el-table-column label="选择">
          <template slot-scope="scope">
            <el-button type="success" icon="el-icon-check" circle @click="addOrder(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <template v-slot:footer>
        <el-button type="primary" @click="submitOrder">确认下单</el-button>
        <el-button @click="isDialogVisible = false">取消</el-button>
      </template>
    </el-dialog>

    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="pageNum"
        :page-sizes="[3, 5, 8]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  name: "MyShoppingCart",
  data() {
    return {
      tab: [],
      pageNum: 1,
      pageSize: 3,
      total: 0,
      selectedBooks: [],
      isDialogVisible: false,
      gridData: [],
      selectedAddress: {},
    };
  },
  methods: {
    addOrder(row){
      this.selectedAddress = {
        receiverName: row.receiverName,
        receiverPhone: row.receiverPhone,
        addressInfo: row.addressInfo
      };
      this.$message.success('地址已选择');
    },
    getAddress() {
      this.$http.post("userAddress/getAddresses")
        .then(resp => {
          console.log(resp)
          this.gridData = resp.data.data;
        })
        .catch(error => {
          console.error('获取收货地址失败:', error);
        });
    },
    fetchData() {
      let formData = new FormData();
      formData.append('pageNum', this.pageNum);
      formData.append('pageSize', this.pageSize);
      this.$http.post('/bookInfo/selectShoppingCart', formData)
        .then(resp => {
          this.tab = resp.data.data.list;
          this.total = resp.data.data.total;
        })
        .catch(err => {
          console.error('获取用户数据失败', err);
        });
    },
    modifyQuantity(bookId, quantity) {
      let formData = new FormData();
      formData.append('bookId', bookId);
      formData.append('number', quantity);
      const apiEndpoint = quantity > 0 ? '/bookInfo/addShoppingCart' : '/bookInfo/DeleteBookFromCart';

      this.$http.post(apiEndpoint, formData)
        .then(response => {
          this.fetchData();
        })
        .catch(error => {
          console.error('更新购物车失败:', error);
        });
    },
    handleSelectionChange(val) {
      this.selectedBooks = val.map(item => item.bookId); // 更新选中的书籍ID
    },
    confirmOrder() {
      if (this.selectedBooks.length === 0) {
        this.$message.warning('请至少选择一件商品');
        return;
      }
      this.getAddress();
      this.isDialogVisible = true;
    },
    submitOrder() {
      if (!this.selectedAddress.receiverName || !this.selectedAddress.receiverPhone || !this.selectedAddress.addressInfo) {
        this.$message.error('请选择一个收货地址');
        return;
      }

      const orderData = {
        bookIds: this.selectedBooks,
        address: this.selectedAddress.addressInfo,
        addressName: this.selectedAddress.receiverName,
        addressPhone: this.selectedAddress.receiverPhone,
      };
      console.log(orderData); // 调试输出，确保数据格式正确
      this.$http.post('/orderInfo/addOrder', orderData)
        .then(response => {
          this.$message.success('订单提交成功！');
          this.isDialogVisible = false;
          this.selectedBooks = [];
          this.selectedAddress = {};
          this.fetchData();
        })
        .catch(error => {
          console.error('订单提交失败:', error);
          this.$message.error('订单提交失败，请重试！');
        });
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.fetchData();
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.fetchData();
    },
  },
  created() {
    this.fetchData();
  }
}
</script>

<style scoped>
.quantity-control {
  display: flex;
  align-items: center;
}

.quantity-display {
  margin: 0 10px;
  font-size: 16px;
  width: 40px;
  text-align: center;
}

.order-actions {
  margin-top: 20px;
  text-align: right;
}
</style>
